﻿using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Web.Mvc;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Serialization;
using System.Globalization;

namespace VisualAgile.Controllers
{
     //<summary>
     //JsonBinder Serializer to convert a JSON Stream from Clientside to a serialized C# Object of based type passed.
     //</summary>
    public class JsonBinder<T> : IModelBinder
    {
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {

            // Get the json that is being passed in.
            string JsonString = controllerContext.HttpContext.Request.Form[bindingContext.ModelName] as string;            

            using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(JsonString)))
            {
                var serializer = new DataContractJsonSerializer(typeof(T));

                return (T)serializer.ReadObject(ms);
            }

            //var param = new DataContractJsonSerializer(typeof(T))
            //    .ReadObject(controllerContext.HttpContext.Request.InputStream);

            //return param;
        }       
    }

    public class JSONBinder<T> : DefaultModelBinder
    {
        //protected override object ConvertType(CultureInfo culture, object value, Type destinationType)
        //{
        //    // Get the json that is being passed in.
        //    string JsonString = value as string;

        //    if (JsonString == null && value is string[])
        //    {
        //        JsonString = ((string[])value)[0];
        //    }

        //    using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(JsonString)))
        //    {
        //        var serializer = new DataContractJsonSerializer(typeof(T));

        //        return (T)serializer.ReadObject(ms);
        //    }
        //}
       
    }
}
